
#include "Logger.h"
#include <chrono>
#include <ctime>

// 来了
std::string getCurrentTime() {
  auto now = std::chrono::system_clock::now();
  std::time_t now_time = std::chrono::system_clock::to_time_t(now);
  char buffer[100];
  std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&now_time));
  return std::string(buffer);
}

Logger& Logger::getInstance(){
  static Logger instance;
  return instance;
};

// RAII思想：构造前把所有资源都初始化好
Logger::Logger(){
  logFile.open("log.txt",std::ios::app);
  if(!logFile.is_open()){
    throw std::runtime_error("Failed to open log fiile");
  }
};

Logger::~Logger(){
  if(logFile.is_open()){
    logFile.close();
  }
};

void Logger::log(const std::string& message){
  std::lock_guard<std::mutex> lock(mutex);
  if(logFile.is_open()){
    // auto now = std::chrono::system_clock::now();
    // auto now_time = std::chrono::system_clock::to_time_t(now);
    // logFile << std::ctime(&now_time) << " " << message <<std::endl;
    logFile << getCurrentTime() << " " << message << std::endl;
  }
};







